﻿using System;
using System.IO;

class Program
{
    static void Main()
    {
        Console.WriteLine("=== Simple OCR with SkiaSharp ===");

        var modelPath = "model.bin";
        SimpleOcr.SimpleNet net;

        var projectDir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.Parent.FullName;
        if (File.Exists(modelPath))
        {
            Console.WriteLine("Loading existing model...");
            net = SimpleOcr.LoadModel(modelPath);
        }
        else
        {
            var trainDir = Path.Combine(projectDir, "training_data");
            Console.WriteLine($"Training new model({trainDir})...");
            net = SimpleOcr.Train(trainDir, epochs: 3, lr: 0.01f);
        }

        var predictDir = Path.Combine(projectDir, "testing_data");
        Console.WriteLine($"\nPredicting({predictDir}) ...");

        var subDirs = Directory.GetDirectories(predictDir).ToList();
        var rng = new Random(452);
        for (int i = 0; i < subDirs.Count; i++)
        {
            var expectLabel = Path.GetFileName(subDirs[i]).First();
            var files = Directory.GetFiles(subDirs[i], "*.png");
            var idx = rng.Next(files.Length);
            var file = files[idx];
            var input = SimpleOcr.ImageToInput(file); // 自动缩放
            int predicted = net.Predict(input);
            var arr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
            var actualLabel = arr[predicted];
            if (expectLabel != actualLabel)
            {
                Console.WriteLine($"Error Expect:{expectLabel} Predicted label: {actualLabel}");
            }
            else
            {
                Console.WriteLine($"Success Expect:{expectLabel} Predicted label: {actualLabel}");
            }
        }

        Console.WriteLine("done");
    }
}
